package cn.sciento.starter.sms.service;

import cn.sciento.core.exception.CommonException;
import com.github.qcloudsms.SmsMultiSenderResult;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import cn.sciento.starter.sms.configuration.SmsConfigProperties;
import cn.sciento.starter.sms.entity.SmsConfig;
import cn.sciento.starter.sms.entity.SmsMessage;
import cn.sciento.starter.sms.entity.SmsReceiver;
import cn.sciento.starter.sms.exception.SendMessageException;
import cn.sciento.starter.sms.support.QcloudSmsSupporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class QcloudSmsServiceImpl extends SmsService {
  private final SmsConfigProperties configProperties;
  
  @Autowired
  public QcloudSmsServiceImpl(SmsConfigProperties configProperties) {
    this.configProperties = configProperties;
  }
  
  public String serverType() {
    return "QCLOUD";
  }
  
  public void smsSend(List<SmsReceiver> receiverAddressList, SmsConfig smsConfig, SmsMessage message, Map<String, String> args) {
    if (this.configProperties.getSms().isFakeAction() && StringUtils.hasText(this.configProperties.getSms().getFakeAccount())) {
      receiverAddressList = Collections.singletonList((new SmsReceiver()).setIdd(this.configProperties.getSms().getFakeIdd())
          .setPhone(this.configProperties.getSms().getFakeAccount()));
    } else if (this.configProperties.getSms().isFakeAction()) {
      return;
    } 
    Map<String, List<SmsReceiver>> receivers = receiverAddressList.stream().peek(item -> {
          if (!StringUtils.hasText(item.getIdd()))
            item.setIdd("+86"); 
        }).collect(Collectors.groupingBy(SmsReceiver::getIdd));
    receivers.forEach((idd, receiver) -> {
          String[] phones = new String[receiver.size()];
          receiver.stream().map(SmsReceiver::getPhone).collect(Collectors.toList()).toArray((Object[])phones);
          idd = idd.replace("+", "");
          String[] params = new String[args.size()];
          List<String> argsList = getTemplateArgs();
          for (int i = 0; i < argsList.size(); i++) {
            String arg = argsList.get(i);
            if (args.containsKey(arg)) {
              params[i] = args.get(arg);
            } else {
              throw new CommonException("No arg found for template " + message.getTemplateCode() + " where arg named " + arg);
            } 
          } 
          SmsMultiSenderResult result = QcloudSmsSupporter.sendSms(QcloudSmsSupporter.multiSender(smsConfig), idd, phones, message.getExternalCode(), params, smsConfig.getSignName());
          if (result.result != 0)
            throw new SendMessageException(result.errMsg); 
        });
    remove();
  }
}
